package org.eden.heartbeat.core.persistence.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eden.heartbeat.core.persistence.ConfigurationDAO;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * The DAO implementation for application configurations.
 *
 * @author trsimoes
 * @version $Revision:$
 */
public class ConfigurationDAOImpl extends AbstractDAOImpl implements ConfigurationDAO {

    private static Log LOG = LogFactory.getLog(ConfigurationDAOImpl.class);

    private final static String QUERY = "SELECT KEY, VALUE FROM CONFIGURATION";

    @Override
    public Map<String, String> getConfiguration() throws SQLException {

        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;

        Map<String, String> results = null;
        try {
            preparedStatement = this.persistenceManager.getConnection().prepareStatement(QUERY);

            resultSet = preparedStatement.executeQuery();

            results = new HashMap<String, String>();

            while (resultSet.next()) {
                String key = resultSet.getString("KEY");
                String value = resultSet.getString("VALUE");
                results.put(key, value);
            }
        } catch (SQLException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("error getting configurations from database", e);
            }
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        }

        return results;
    }
}